package com.bluebench.bigul.service.resolver;

import java.util.List;

import com.bluebench.bigul.domain.Element;
import com.bluebench.bigul.domain.Element.Attribute;
import com.bluebench.bigul.domain.Element.Parameter;
import com.bluebench.bigul.domain.FormData;
import com.bluebench.bigul.domain.Tag;
import com.bluebench.bigul.exception.GraphicInitializationException;


public class SubstitutionExpressionResolver extends DefaultExpressionResolver{
	
	private static FormData formData;
	
	public SubstitutionExpressionResolver(){	
	}
	public SubstitutionExpressionResolver(FormData formdata){
		formData = formdata;
	}
	public SubstitutionExpressionResolver(FormData formdata,Element element){
		formData = formdata;
		tag = element;
	}	
	
	@Override
	public void resolve() throws GraphicInitializationException {
		switch(tag.getElementType()){
		
		case ELEMENT:
			Element element = (Element)tag;
			List<Element> elementList = element.getElements();
			resolveElements(elementList);
			
			List<Attribute> attributeList= element.getAttributes();
			if(attributeList!=null){
				resolveAttributes(attributeList);
			}
			break;
		case ATTRIBUTE:
			Attribute attribute = (Attribute)tag;
			List<Parameter> parameterList = attribute.getParameters();
			if(parameterList!=null && (!parameterList.isEmpty())){
				resolveParameter(parameterList);
			}
			break;
		case PARAMETER:
			resolveExpression(tag.getExpression());
			break;
		
		}
		
	}
	
	
	private void resolveElements(List<Element> elementList) throws GraphicInitializationException{
		for(Element e : elementList){
			e.setResolver(getInstance(SUBSTITUTION_RESOLVER));
			e.resolve();
		}
	}
	
	private void resolveAttributes(List<Attribute> attributeList) throws GraphicInitializationException{
		for(Attribute a : attributeList){
			a.setResolver(getInstance(SUBSTITUTION_RESOLVER));
			a.resolve();
		}
	}
	
	private void resolveParameter(List<Parameter> parameterList) throws GraphicInitializationException{
		for(Parameter p : parameterList){
			Object o = p.getValue();
			if(o instanceof Element){
				Element e = (Element)o;
				e.setResolver(getInstance(SUBSTITUTION_RESOLVER));
				e.resolve();
			}else{
				resolveSubstitution(p);
			}
		}
	}	
	
	public void resolveSubstitution(Tag t) {
		Parameter p = (Parameter)t;
		String expression = p.getValue().toString(); 
		if(formData!=null && validate(expression)){
			String s = formData.getFieldValue(expression.replace(":",""));
			PrimitiveExpressionResolver.setParameterValue(p,s);
		}else{
			//TODO : Throw Exception
		}
	}
	
	@Override
	public boolean validate(String expression) {
		return formData.isKey(expression.replace(":",""));		
	}
	
	public void setFormData(FormData formData){
		SubstitutionExpressionResolver.formData=formData;
	}
	
	
	

}
